package com.ipet.web.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ipet.web.pojo.Cart;
import com.ipet.web.service.CartService;
import com.ipet.web.util.UserThreadLocal;


@Controller
@RequestMapping("/cart")
public class CartController {
	
	@Autowired
	private CartService cartService;
	
	@RequestMapping("/show")
	public String findCartByUserId(Model model){
		Long userId =  UserThreadLocal.getUser().getId();
		List<Cart> cartList = cartService.findCartByUserId(userId);
		model.addAttribute("cartList",cartList);
		return "cart";
	}
	
	//修改购物车商品数量		 http://www.jt.com/service/cart/update/num/1474391949/2
	@RequestMapping(value="/update/num/{itemId}/{num}",method=RequestMethod.POST)
	@ResponseBody
	public String updateCartNum(@PathVariable Long itemId,@PathVariable Integer num){
		Long userId =  UserThreadLocal.getUser().getId();
		Cart cart = new Cart();	//为属性赋值
		cart.setUserId(userId);	
		cart.setItemId(itemId);
		cart.setNum(num);
		
		cartService.updateCartNum(cart);
		return null;
	}
	
	//删除购物车
	@RequestMapping(value="/delete/{itemId}",method=RequestMethod.GET)
	public String deleteCart(@PathVariable Long itemId){
		Long userId =  UserThreadLocal.getUser().getId();
		cartService.deleteCart(userId,itemId);
		
		//跳转到购物车列表页面	满足springMVC的要求 *.html
		return "redirect:/cart/show.html";
	}
	
	@RequestMapping(value="/add/{itemId}",method=RequestMethod.POST)
	public String addCart(@PathVariable Long itemId,Cart cart){
		Long userId =  UserThreadLocal.getUser().getId();
		//将数据进行封装
		cart.setUserId(userId);
		cart.setItemId(itemId);
		cartService.addCart(cart);
		//转向购物车展现页面
		return "redirect:/cart/show.html";
		
	}
	
}
